// 登录和注册
const express = require('express')
const router = express.Router()
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/nodeData';
const gravatar = require('gravatar');
const jwt = require('jsonwebtoken');
const passport = require('passport');

router.get('/test', (req, res) => {
    res.json({
        msg: "login"
    })
});

//注册
router.post('/register', (req, res) => {
    console.log("注册参数:",req.body)
    MongoClient.connect(url, { useNewUrlParser: true }, function (err, db) {
        if (err) throw err;
        const avatar = gravatar.url(req.body.email, {s: '200', r: 'pg', d: 'mm'});
        var dbo = db.db("nodeData");
        var usersName = {
            name: req.body.name,
            pwd: req.body.password,
            avatar: avatar,
            email:req.body.email,
            identity:req.body.identity,
            date:Date.now
        };

        dbo.collection("site").findOne({email:req.body.email}, function (err, reson) {
            console.log("是否有重复数据:",reson)
            if(reson){
                res.status(400).json({email:"邮箱已经被注册"})
            }else{
                dbo.collection("site").insertOne(usersName, function (err, resonIn) {
                    if (err) throw err;
                    res.status(200).json({usersName})
                });
            }
            db.close();
        });
    });
});

//登录
router.post('/login',(req,res)=>{
    const email = req.body.email;
    const pwd = req.body.password;
    MongoClient.connect(url,{useNewUrlParser: true},(err,db)=>{
        if(err) throw err;
        var dbo = db.db("nodeData");
        dbo.collection('site').findOne({email},(siterr,users)=>{
            console.log("查询是否有数据:",users)
            if(!users){
                res.status(404).json({email:"账号不存在！！！"});
            }else{
                if(pwd === users.pwd){
                    const rule = {
                        id:users._id,
                        name:users.name,
                        avatar:users.avatar,
                        identity:users.identity
                    };
                    jwt.sign(rule,'secret',{expiresIn:3600},(jwtErr,token)=>{
                        if(jwtErr) throw jwtErr;
                        res.json({
                            success:"登录成功",
                            token:'Bearer '+token
                        })
                    })
                }else{
                    res.status(200).json({email:"账号或者密码错误"});
                }
            }
        })
    })
});

//验证token
router.get('/current',passport.authenticate("jwt",{session:false}),(req,res)=>{
    res.json({msg:"验证成功",data:req.user});
});

module.exports = router;